package com.he.shiro;


import cn.hutool.core.bean.BeanUtil;
import com.he.entity.User;
import com.he.service.UserService;
import com.he.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author Kris He
 * @date 2022/03/20 19:39
 **/
@Component
public class AccountRealm extends AuthorizingRealm {

    @Autowired
    JwtUtils jwtUtils;

    @Autowired
    UserService userService;

    @Override
    public boolean supports(AuthenticationToken token) {
        //支持的是JwtToken，而不是其他类型的Token，因此需要是JwtToken的类型或者子类
        return token instanceof JwtToken;
    }

    //拿到用户之后，进行权限认证，完成后将信息进行封装成AuthorizationInfo给shrio
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        return null;
    }

    //拿到token，进行身份认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) token;
        Claims claim = jwtUtils.getClaimByToken((String) jwtToken.getPrincipal());
        //userId通常在claim的subject里面
        String userId = claim.getSubject();
        User user = userService.getById(Long.valueOf(userId));
        if (user == null){
            throw new UnknownAccountException("账户不存在");
        }
        if (user.getStatus() == -1){
            throw new LockedAccountException("账户已被锁定");
        }
        AccountProfile profile = new AccountProfile();
        //把user的的信息全部拷贝给profile
        BeanUtil.copyProperties(user,profile);
        //接着把上面的信息返回给shiro，这些是可以公开的信息，如果比较私密的就不会公开，因此要封装一个类AccountProfile
        return new SimpleAuthenticationInfo(profile,jwtToken.getCredentials(),getName());
    }
}
